#!/bin/sh
function Error_Msg()
{
    error_msg=$1
    echo error_message=$error_msg
    curl -H "Content-Type:application/json"  -X POST --data  '{"errorinfo": [{"error_message":"'"$error_msg"'","jid":"'$rp_jid'"}]}'  "$notify_url"
    exit 1
}


function phoenix_app_special_channels()
{
    tool_path="/root/helen/scripts"
    echo app_name=$1 and channel=$2
    if [ "$2" != "alibaba" -a "$2" != "damai_inner" -a "$2" != "damai_oversea"  -a "$2" != "skyworthbox" -a "$2" != "imilab" -a "$2" != "xiaomi" ];then
        echo not alibaba, damai_inner,damai_oversea,skyworthbox,imilab,xiaomi channel, so do nothing and return
        return #只处理以上渠道，其他渠道不处理
    fi
    if [ -d sign_apk_tool ];then
        echo delete sign_apk_tool
        rm sign_apk_tool -rf
    fi
    mkdir sign_apk_tool
    mv target/$1 sign_apk_tool/
    cd sign_apk_tool/
    old_apk=$1
    new_channel=$2
    old_apk_name=`echo $old_apk |awk -F ".apk" '{print $1}'`
    echo old_apk_name=$old_apk_name

    echo ================================apktool decompile===========================
    java -jar $tool_path/apktool.jar d $old_apk
    echo delete $old_apk ...
    rm $old_apk

     #大麦(1)修改apk名字,(2)替换bg_main_video.png(3)替换优化页(4)替换icon(5)替换启动页(6)替换devicename.txt文件
    if [ "$2" == "damai_inner" -o "$2" == "damai_oversea" ];then
        echo $2 channel need to change app name and add damai
        sed -i s/app_name\"\>/app_name\"\>Damai/g   $old_apk_name/res/values/strings.xml
        sed -i s/app_name\"\>/app_name\"\>"大麦"/g   $old_apk_name/res/values-zh-rCN/strings.xml
        sed -i s/app_name\"\>/app_name\"\>"大麥"/g   $old_apk_name/res/values-zh-rHK/strings.xml
        sed -i s/app_name\"\>/app_name\"\>"大麥"/g   $old_apk_name/res/values-zh-rTW/strings.xml
        echo change result as follow:
        grep -rn app_name $old_apk_name/res/* |grep -v public.xml

        echo replace bg_main_video.png_12K and result as follow:
        cp $tool_path/damai/bg_main_video.png $old_apk_name/res/mipmap-xxhdpi-v4/bg_main_video.png
        du -sh  $old_apk_name/res/mipmap-xxhdpi-v4/bg_main_video.png

        echo replace cast_optimize.png_608k and result as follow:
        cp $tool_path/damai/cast_optimize.png $old_apk_name/res/drawable/cast_optimize.png
        du -sh $old_apk_name/res/drawable/cast_optimize.png

        echo replace lunch page_104k and result as follow:
        cp $tool_path/damai/damai_lunch_pg.png   $old_apk_name/res/mipmap-xhdpi-v4/lunch_bg.png
        du -sh $old_apk_name/res/mipmap-xhdpi-v4/lunch_bg.png

        echo replace devicename.txt and result as follow:
        cp $tool_path/damai/devicenames.txt   $old_apk_name/res/raw/devicenames.txt
        cat $old_apk_name/res/raw/devicenames.txt
        echo

    fi

    #alibaba使用不同的图标
    if [ "$2" == "alibaba" ];then
        echo alibaba change to different icon_68k
        rm $old_apk_name/res/mipmap-xhdpi-v4/lebo_game_icon.png
        cp  $tool_path/ali/ali_icon.png  $old_apk_name/res/mipmap-xhdpi-v4/lebo_game_icon.png
        du -sh $old_apk_name/res/mipmap-xhdpi-v4/lebo_game_icon.png
    fi

    #替换图标为大麦的图标
    if [ "$2" == "damai_oversea" -o  "$2" == "damai_oversea" ];then
        echo $2 replace icon_20K and result as follow:
        rm $old_apk_name/res/mipmap-xhdpi-v4/lebo_game_icon.png
        cp $tool_path/damai/damai_icon.png  $old_apk_name/res/mipmap-xhdpi-v4/lebo_game_icon.png
        du -sh $old_apk_name/res/mipmap-xhdpi-v4/lebo_game_icon.png
    fi
    #创维盒子修改：
    #（1）应用名称修改为投屏教程
    #（2）投屏优化指南： 将文字中"电视“换成 ”创维盒子“;同时去掉淘宝扫一扫的二维码；电视图像旁边增加创维盒子的图像
    if [ "$2" == "skyworthbox" ];then
        echo $2 need to change app name
        sed -i s/app_name\"\>HappyCast/app_name\"\>"Multi-Screen"/g   $old_apk_name/res/values/strings.xml
        sed -i s/app_name\"\>乐播投屏/app_name\"\>"投屏教程"/g   $old_apk_name/res/values-zh-rCN/strings.xml
        sed -i s/app_name\"\>樂播投屏/app_name\"\>"投屏教程"/g   $old_apk_name/res/values-zh-rHK/strings.xml
        sed -i s/app_name\"\>樂播投屏/app_name\"\>"投屏教程"/g   $old_apk_name/res/values-zh-rTW/strings.xml
        echo change result as follow:
        grep -rn app_name $old_apk_name/res/* |grep -v public.xml
        echo replace cast_optimize.png_608k and result as follow:
        cp $tool_path/skyworthbox/cast_optimize.png $old_apk_name/res/drawable/cast_optimize.png
        du -sh $old_apk_name/res/drawable/cast_optimize.png
        echo replace lunch page_292k and result as follow:
        cp $tool_path/skyworthbox/skyworthbox_lunch_pg.png   $old_apk_name/res/mipmap-xhdpi-v4/lunch_bg.png
        du -sh $old_apk_name/res/mipmap-xhdpi-v4/lunch_bg.png
    fi
    #创米去掉水印，关闭水印开关
    if [ "$2" == "imilab" ]; then
        echo imilab need to close switch_watermark
        sed -i s/switch_watermark\"\>1/switch_watermark\"\>0/g   $old_apk_name/res/values/strings.xml
        echo change result as follow:
        grep -rn "switch_watermark" $old_apk_name/res/values/strings.xml
    fi
    #小米替换icon
    if [ "$2" == "xiaomi" ];then
        echo xiaomi change to different icon_140k
        rm $old_apk_name/res/mipmap-xhdpi-v4/lebo_game_icon.png
        cp  $tool_path/xiaomi/xiaomi_icon.png  $old_apk_name/res/mipmap-xhdpi-v4/lebo_game_icon.png
        du -sh $old_apk_name/res/mipmap-xhdpi-v4/lebo_game_icon.png
    fi
    #当贝投影修改：（1）app名称为当贝投屏（2）修改启动页 （3）修改icon
    if [ "$2" == "dangbei_touying"  ];then
        echo $2 need to change app name
        sed -i s/app_name\"\>HappyCast/app_name\"\>"DangbeiCast"/g   $old_apk_name/res/values/strings.xml
        sed -i s/app_name\"\>乐播投屏/app_name\"\>"当贝投屏"/g   $old_apk_name/res/values-zh-rCN/strings.xml
        sed -i s/app_name\"\>樂播投屏/app_name\"\>"當貝投屏"/g   $old_apk_name/res/values-zh-rHK/strings.xml
        sed -i s/app_name\"\>樂播投屏/app_name\"\>"當貝投屏"/g   $old_apk_name/res/values-zh-rTW/strings.xml
        echo change result as follow:
        grep -rn app_name $old_apk_name/res/* |grep -v public.xml
        echo replace dangbei_ty_icon.png_20k and result as follow:
        cp $tool_path/dangbei_ty/dangbei_ty_icon.png $old_apk_name/res/mipmap-xhdpi-v4/lebo_game_icon.png
        du -sh $old_apk_name/res/mipmap-xhdpi-v4/lebo_game_icon.png
        echo replace lunch page_388k and result as follow:
        cp $tool_path/dangbei_ty/dangbei_ty_lunch_pg.png   $old_apk_name/res/mipmap-xhdpi-v4/lunch_bg.png
        du -sh $old_apk_name/res/mipmap-xhdpi-v4/lunch_bg.png
    fi

    echo ==============================delete META-INF ===================
    rm -rf $old_apk_name/original/META-INF
    echo ================================apktool compile============================
    java -jar $tool_path/apktool.jar b $old_apk_name
    mv $old_apk_name/dist/$old_apk ./

#echo setting alias .....
#keytool -list -v -keystore mirrorcast_aw.key -alias mirrorcast_aw -storepass mirrorcastisgood
    echo ===================================sign====================================
    jarsigner -verbose -digestalg SHA1 -sigalg SHA1withRSA -keystore $tool_path/mirrorcast_aw.key -signedjar "$old_apk_name".apk $old_apk mirrorcast_aw -storepass mirrorcastisgood

    echo ==================================checking sign=============================
#jarsigner -certs -verbose -verify "$old_apk_name"_signed.apk
    jarsigner -certs -verify "$old_apk_name".apk
    mv "$old_apk_name".apk  ../target/"$old_apk_name".apk
    cd ../
    du -sh target/*
    echo cur_path=`pwd`
}

sed -i 's/,/\n/g' user_config
source /etc/profile
echo jenkins var as follow:
echo build_num=$BUILD_NUMBER
echo build_user_id=$BUILD_USER_ID
echo build_user=$BUILD_USER
echo job_name=$JOB_NAME
#app 要放到cibn上
#cdn_url="http://cdn1.hpplay.cn"
cdn_url="http://download.mirrorcast.cn"
cibn_ftp_server="$cdn_url/release"
cibn_ftp_path="lebo@47.106.144.141:/lebosource/apk/release"
#cibn_ftp_psw="source!@#321" #CIBN密码
cibn_ftp_psw="Pass@123(*)" #CIBN密码
#cibn_ftp_server_test="http://source.hpplay.cn/test"
cibn_ftp_server_test="$cdn_url/test"
cibn_ftp_path_test="lebo@47.106.144.141:/lebosource/apk/test"

notify_url_release="http://120.78.19.55:9201/JenkinsCallback"
#notify_url_test="http://120.79.212.106:9201/JenkinsCallback"
#notify_url_test="http://120.79.212.106:9201/JenkinsCallback"
notify_url_test="http://58.250.17.73:9201/JenkinsCallback"

if [ "$JOB_NAME" != "Phoenix-App" ];then #测试工程app
    echo ====================Test Project===========
    ftp_server=$cibn_ftp_server_test
    ftp_path=$cibn_ftp_path_test
    ftp_psw=$cibn_ftp_psw
    notify_url=$notify_url_test
else #正式工程app
    ftp_server=$cibn_ftp_server
    ftp_path=$cibn_ftp_path
    ftp_psw=$cibn_ftp_psw
    notify_url=$notify_url_release
fi

rp_build_path=`grep  build_aliyun_path user_config |awk -F '=' '{print $2}'`
rp_build_appid=`grep  build_appid user_config |awk -F '=' '{print $2}'`
rp_build_secret=`grep  build_secret user_config |awk -F '=' '{print $2}'`
rp_jid=`grep jid user_config |awk -F '=' '{print $2}'`
rp_build_channel=`grep build_appname user_config |awk -F '=' '{print $2}' |sed s/" "//g` #删除空格
echo user config as follow:
cat user_config
echo current path is `pwd`
echo get build_path=$rp_build_path,build_appid=$rp_build_appid,build_secret=$rp_build_secret,jid=$rp_jid,build_appname=$rp_build_channel
echo env config as follow:
echo ftp_server=$ftp_server
echo ftp_path=$ftp_path
echo notify_url=$notify_url
#jianguo_up: (jianguo升级渠道)
#app_id=10657
#leupgrade: (升级专用渠道)
#app_id=10480
#coocaa: (酷开)
#app_id=2010
#Haier: (海尔)
#app_id=2039
#这几个特殊渠道都是本地打包的，所以不允许在乐播云上取包
if [ "$rp_build_appid" == "10657" -o "$rp_build_appid" == "10480" -o "$rp_build_appid" == "2010" -o "$rp_build_appid" == "2039" ];then 
    error_message="$rp_build_appid is special channel and cannot download at lebo cloud"
    Error_Msg "$error_message"
fi
[ "x$rp_build_appid" == "x" ] && error_message="appid is null" && Error_Msg "$error_message"

[ "x$rp_build_secret" == "x" ] && error_message="secret is null" && Error_Msg "$error_message"

[ "x$rp_build_path" == "x" ] &&	error_message="aliyun path is null" && Error_Msg "$error_message"

[ "x$rp_build_channel" == "x" ] && error_message="channel name is null" && Error_Msg "$error_message"

rec_flag=`echo $rp_build_path |grep "phoenix_app"`
send_flag=`echo $rp_build_path |grep "phoenix_send_app"`
echo rec_flag=$rec_flag and send_flag=$send_flag
[ "x$rec_flag" == "x" -a "x$send_flag" == "x" ] && error_message="aliyun path is not phoenix rec app nor phoenix send app" && Error_Msg "$error_message"

apk_name_tmp=`echo $rp_build_path |awk -F 'hpplay-' '{print $2}'`
apk_name=hpplay-"$apk_name_tmp"
echo apk_name=$apk_name
echo download release app:
#echo "curl -o $apk_name $rp_build_path"
#curl -o $apk_name  $rp_build_path
echo "wget -O $apk_name $rp_build_path"
wget -O $apk_name  $rp_build_path
[ $? -ne 0 ] && error_message="download aliyun path file failed,maybe path is not right" && Error_Msg "$error_message"
[ ! -f $apk_name ] && error_message="download aliyun path file failed,maybe path is not right" && Error_Msg "$error_message"
echo `pwd` apk as follow: `ls | grep apk`

new_apk_name=`ls |grep ".apk$" |awk -F ".apk" '{print $1}' `
echo new app name=$new_apk_name
[ "x$new_apk_name" == "x" ] &&	error_message="have no .apk file" && Error_Msg "$error_message"
mkdir target
mv "$new_apk_name".apk target/
if [ "x$rec_flag" != "x" ];then
    phoenix_app_special_channels "$new_apk_name".apk "$rp_build_channel"
    recapp_path=phoenix_app
fi

[ "x$send_flag" != "x" ] && recapp_path=phoenix_send_app
mv target/"$new_apk_name".apk ./

mkdir apk_output
mkdir META-INF
touch META-INF/appid_$rp_build_appid
touch META-INF/secret_$rp_build_secret
touch META-INF/channel_"$rp_build_channel"
echo new MRTA-INF file as follow:`ls META-INF`
echo "file type as follow (file command returen empty means empty file ):"
file META-INF/appid_$rp_build_appid
file META-INF/secret_$rp_build_secret
file META-INF/channel_"$rp_build_channel"
echo zip add null file to "$new_apk_name".apk
zip -m "$new_apk_name".apk ./META-INF/*

time_now=`date "+%Y%m%d%H%M"`
new_apk_name2=`ls |grep ".apk$" |awk -F ".apk" '{print $1}' |sed s/happytest/$rp_build_appid/g `
app_ver=`ls |grep ".apk$" |awk -F "-v" '{print $2}' |awk -F ".apk" '{print $1}' |awk -F "_" '{print $1}' | sed 's/\.//g' `
#echo "mv "$new_apk_name".apk apk_output/"$new_apk_name2".apk"
echo ==================zipalign===================
zipalign_command="/usr/local/sdk/build-tools/25.0.3/zipalign"
$zipalign_command -v 4 "$new_apk_name".apk apk_output/"$new_apk_name2".apk
rm "$new_apk_name".apk
#mv "$new_apk_name".apk apk_output/"$new_apk_name2".apk
cd apk_output
md5sum "$new_apk_name2".apk > md5sum.txt
echo apk md5sum as follow:
cat md5sum.txt
upload_app="$time_now"_"$recapp_path"_"$rp_build_appid"_"$rp_build_channel"_"$app_ver"
zip -r "$upload_app".zip "$new_apk_name2".apk md5sum.txt
zip_md5sum=`md5sum "$upload_app".zip |awk -F " " '{print $1}'`
echo zip empty file to apk as follow:

mkdir unzip_apk
unzip  -q "$new_apk_name2".apk -d unzip_apk/
ls unzip_apk/META-INF/
if [ -f unzip_apk/META-INF/appid_$rp_build_appid ];then
    echo target file appid_$rp_build_appid in unzip META-INF ,success!
else
    error_message="target file appid_$rp_build_appid not in unzip META-INF ,fail"
    Error_Msg "$error_message"
fi
tapp_name="$time_now"_"$new_apk_name2".apk
mv "$new_apk_name2".apk $tapp_name
app_md5sum=`md5sum $tapp_name |awk -F " " '{print $1}'`
echo will upload file "$upload_app".zip and $tapp_name to ftp server dir $recapp_path
echo upload file info as follow:
du -sh "$upload_app".zip
du -sh $tapp_name
start_time=`date +%s`
sshpass -p $ftp_psw  scp  "$upload_app".zip $ftp_path/$recapp_path/
[ $? -ne 0 ] && error_message="upload to cdn failed,exit" && Error_Msg "$error_message"
recapp_download="$ftp_server/$recapp_path/"$upload_app".zip"
sshpass -p $ftp_psw  scp  $tapp_name  $ftp_path/$recapp_path/
[ $? -ne 0 ] && error_message="upload to cdn failed,exit" && Error_Msg "$error_message"
apk_download="$ftp_server/$recapp_path/$tapp_name"
echo download_path=$recapp_download
echo download_apk_path=$apk_download
end_time=`date +%s`
cost=$(( $end_time - $start_time ))
echo "upload Done. Total costs $cost seconds."
echo
curl -H "Content-Type:application/json"  -X POST --data '{"dlinfo": [{"result_path": "'$recapp_download'","jid": "'$rp_jid'","aversion": "'$app_ver'","bversion": "null","furl": "'$recapp_download'","fmd5": "'$zip_md5sum'","apkurl":"'$apk_download'","apkmd5":"'$app_md5sum'","purl": "null","pmd5": "null" }]}' $notify_url -v  

#sshpass -p "lebo123"  scp -v "$upload_app" $FTP_DIR/$recapp_path/
#scp -o GSSAPIAuthentication=no -c arcfour128  -v "$upload_app" root@120.76.155.128:/lebores/jenkins_result/$recapp_path/
#sshpass -p "lebo123"  rsync -av --progress  "$upload_app" $FTP_DIR/$recapp_path/
#cp -f /root/helen/scripts/expect_scp ./
#ftp_pwd="/lebores/jenkins_result"
#./expect_scp 120.76.155.128  "lebotest" "lebo123"  "$upload_app" $ftp_pwd/$recapp_path/
